// 添加DOMContentLoaded事件监听器
document.addEventListener('DOMContentLoaded', function() {
    const likeBtn = document.getElementById('likeBtn');
    const submitCommentBtn = document.getElementById('submitCommentBtn');
    const commentsList = document.querySelector('.comments-list');
    const postId = window.location.pathname.split('/').pop();
    
    // 加载评论
    loadComments();
    
    // 点赞按钮事件
    likeBtn.addEventListener('click', function() {
        fetch(`/api/posts/${postId}/like`, {
            method: 'POST'
        })
        .then(response => {
            if (!response.ok) {
                if (response.status === 400) {
                    return response.json().then(data => {
                        throw new Error(data.message || '您已经点赞过此帖子');
                    });
                }
                throw new Error('点赞失败');
            }
            return response.json();
        })
        .then(data => {
            // 更新点赞数
            const likeCountElement = likeBtn.querySelector('span');
            likeCountElement.textContent = data.data.likeCount;
            
            // 添加点赞动画效果
            likeBtn.classList.add('liked');
            setTimeout(() => {
                likeBtn.classList.remove('liked');
            }, 1000);
        })
        .catch(error => {
            console.error('点赞请求失败:', error);
            alert(error.message || '点赞失败，请重试');
        });
    });
    
    // 提交评论事件
    submitCommentBtn.addEventListener('click', function() {
        const commentText = document.getElementById('commentText').value.trim();
        
        if (!commentText) {
            alert('请输入评论内容');
            return;
        }
        
        fetch(`/api/comments/posts/${postId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ content: commentText })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('评论失败');
            }
            return response.json();
        })
        .then(data => {
            // 清空评论输入框
            document.getElementById('commentText').value = '';
            
            // 重新加载评论
            loadComments();
            
            // 更新评论数（在实际项目中，这个数字应该从服务器获取）
            const commentCountElement = document.querySelector('.comment-btn span');
            const currentCount = parseInt(commentCountElement.textContent);
            commentCountElement.textContent = currentCount + 1;
        })
        .catch(error => {
            console.error('评论请求失败:', error);
            alert('评论失败，请重试');
        });
    });
    
    // 加载评论函数
    function loadComments() {
        fetch(`/api/comments/posts/${postId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('加载评论失败: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            // 验证数据是否为数组
            if (Array.isArray(data)) {
                renderComments(data);
            } else {
                console.error('评论数据格式不正确:', data);
                commentsList.innerHTML = '<p class="comment-error">加载评论失败，请重试</p>';
            }
        })
        .catch(error => {
            console.error('加载评论请求失败:', error);
            commentsList.innerHTML = `<p class="comment-error">${error.message}</p>`;
        });
    }
    
    // 渲染评论函数
    function renderComments(comments) {
        commentsList.innerHTML = '';
        
        comments.forEach(comment => {
            const commentElement = document.createElement('div');
            commentElement.className = 'comment-item';
            
            // 确保头像路径正确 - 添加完整的路径处理逻辑
            let avatarPath = '/images/default-avatar.jpg'; // 默认头像
            if (comment.user.avatar) {
                // 检查路径是否已经包含前缀
                if (comment.user.avatar.startsWith('/')) {
                    avatarPath = comment.user.avatar; // 已经是绝对路径
                } else {
                    avatarPath = '/uploads/' + comment.user.avatar; // 添加前缀
                }
            }
            
            commentElement.innerHTML = `
                <img src="${avatarPath}" alt="评论者头像" class="commenter-avatar">
                <div class="comment-content">
                    <div class="comment-header">
                        <span class="commenter-name">${comment.user.username}</span>
                        <span class="comment-time">${formatDate(comment.createdAt)}</span>
                    </div>
                    <p class="comment-text">${comment.content}</p>
                    <div class="comment-actions">
                        <button class="reply-btn" data-comment-id="${comment.id}">回复</button>
                        <button class="like-comment-btn" data-comment-id="${comment.id}">点赞</button>
                    </div>
                </div>
            `;
            
            commentsList.appendChild(commentElement);
        });
        
        // 如果没有评论，显示提示信息
        if (comments.length === 0) {
            commentsList.innerHTML = '<p class="no-comments">暂无评论，快来抢沙发吧！</p>';
        }
    }
    
    // 格式化日期函数
    function formatDate(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        const diffDays = Math.floor(diffMs / 86400000);
        
        if (diffMins < 60) {
            return `${diffMins}分钟前`;
        } else if (diffHours < 24) {
            return `${diffHours}小时前`;
        } else if (diffDays < 30) {
            return `${diffDays}天前`;
        } else {
            return date.toLocaleDateString();
        }
    }
    
    // 视频播放控制
    const video = document.querySelector('video');
    if (video) {
        // 视频播放结束后自动循环
        video.addEventListener('ended', function() {
            this.currentTime = 0;
            this.play();
        });
    }
});